<template>
  <div class="upload-test">
    <input
      type="file"
      ref="import-files"
      style="display: none"
      @change="uploads"
    />
    <div @click="uploadFile">
      <slot name="button" v-if="$slots.button"></slot>
      <el-button v-else type="primary" class="btn" icon="el-icon-upload">导入</el-button>
    </div>
  </div>
</template>

<script>
/**
 * auth fndbs1314
 * des excel (单文件上传)
 * edit 增加自定义上传按钮样式 2020/3/19
 * @slot button 上传显示的标签
 * @props id 标签标志
 * @props uploadUrl 上传路径 /user/file/uploads
 * @emit list: list
 */
import axios from "@/api/__http__.js";
export default {
  name: "FtImport",
  props: {
    uploadUrl: String, // 上传地址
    success: Function, // 成功回调
    error: Function, // 失败回调
    uploadFn: Function, // 自定义上传函数
  },
  methods: {
    uploadFile() {
      this.$refs["import-files"].value = null;
      this.$refs["import-files"].click();
    },
    uploads(e) {
      // 整理上传文件信息
      let e_files = e.target.files;
      let formData = new FormData();
      e_files.forEach((i) => {
        let newFile = new File([i], encodeURIComponent(i.name));
        formData.append("file", newFile);
      });
      // 是否走自定义上传方法
      if (this.uploadFn) {
        this.uploadFn(formData);
        return;
      }
      // 内置上传方法
      axios
        .post({
          url: this.uploadUrl,
          data: formData,
        })
        .then((result) => {
          this.success?this.success(result): null;
          this.reset();
        })
        .catch((err) => {
          this.error?this.error(err):null;
          this.reset();
        });
    },
    // 重置上传按钮
    reset() {
      this.$refs["import-files"].value = null;
      this.$forceUpdate();
    },
  },
};
</script>

<style>
.upload-test {
  display: inline-block;
}
.upload-test .btn {
  min-width: 98px;
  font-size: 14px;
  padding: 8px;
  height: 32px;
  /* margin-left: 0; */
  margin-right: 13px;
}
.upload-test .el-upload-list--picture-card .el-upload-list__item {
  width: 70px;
  height: 70px;
}
</style>
